package com.yonyou.brigade.order_center.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yonyou.brigade.order_center.dao.BriCarOrderMapper;
import com.yonyou.brigade.order_center.model.BriCarOrder;
import com.yonyou.brigade.order_center.model.BriCarOrderDTO;
import com.yonyou.brigade.order_center.model.CnvCarOrderDO;
import com.yonyou.brigade.order_center.model.InvoiceRelationship;
import com.yonyou.brigade.order_center.service.IBriCarOrderService;
import com.yonyou.brigade.order_center.service.IInvoiceRelationshipService;
import com.yonyou.brigade.order_center.util.OrderConvert;
import com.yonyou.brigade.util.operateutil.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiangzhf@yonyou.com
 * @since 2019-01-24
 */
@Service
public class BriCarOrderServiceImpl extends ServiceImpl<BriCarOrderMapper, BriCarOrder> implements IBriCarOrderService {

    @Autowired
    private BriCarOrderMapper briCarOrderMapper;

    @Autowired
    private IInvoiceRelationshipService relationshipService;

    public List<BriCarOrder> getOrdersByRelateYBZId(List<String> ybzIds)
    {
        if(ybzIds!=null&&ybzIds.size()>0) {
            return briCarOrderMapper.getCarOrdersByRelateYBZIds(ybzIds);
        }
        else
        {
            return  new ArrayList<BriCarOrder>();
        }
    }

    @Override
    public Map getBriCarOrderDTOs(Map params) {
        Map queryParams = new HashMap();
        queryParams = params;
        queryParams.put("tenant",params.get("tenantId"));
        int pageSize = Integer.parseInt(params.get("pageSize").toString());
        int current = Integer.parseInt(params.get("current").toString());
        if(pageSize <= 0) {
            pageSize = 10;
        }
        if(current <= 0) {
            current = 1;
        }
        int begin = (current-1)*pageSize;
        queryParams.put("begin",begin);
        queryParams.put("pageSize",pageSize);
        Map result = new HashMap();
        try {
            List<BriCarOrderDTO> briCarOrderDTOS = briCarOrderMapper.getBriCarOrderDTOs(queryParams);
            int total = briCarOrderMapper.getBriCarOrderDTOsCount(queryParams);
            List<BriCarOrderDTO> briCarOrderDTOList = perfectCarOrderDTOs(briCarOrderDTOS);
            result.put("information",briCarOrderDTOList);
            result.put("code","0");
            JSONObject pagination = new JSONObject();
            pagination.put("total",total);
            pagination.put("pageSize",pageSize);
            pagination.put("current",current);
            result.put("pagination",pagination);
        } catch (Exception e) {
            result.put("code","100");
            result.put("information","操作失败");
        }
        return  result;
    }

    @Override
    public List<CnvCarOrderDO> getCnvCarOrderDos(Map<String, String> params, Date beginDate, Date endDate) {
        List<CnvCarOrderDO> cnvCarOrderDOList = new ArrayList<>();
        // 根据条件查询所有的订单
        Wrapper<BriCarOrder> carOrderWrapper = new EntityWrapper<>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            carOrderWrapper.eq(entry.getKey(), entry.getValue());
        }
        carOrderWrapper.between("departure_time", beginDate, DateUtils.strToDateTime(DateUtils.plusDay(1, endDate)));
        carOrderWrapper.ne(true,"is_note",1);
        carOrderWrapper.eq(true, "public_or_private", "1");
        carOrderWrapper.ne(true,"order_no","");
        carOrderWrapper.ne(true,"category","");

        List<BriCarOrder> briCarOrderList = briCarOrderMapper.selectList(carOrderWrapper);
        ArrayList<String> CompletedOrderStatus = new ArrayList<String>(Arrays.asList("2","7","14"));
        if (briCarOrderList != null && briCarOrderList.size() > 0) {
            for (BriCarOrder briCarOrder : briCarOrderList) {
                // 过滤订单状态
                if (StringUtils.isNotBlank(briCarOrder.getOrderStatus()) && CompletedOrderStatus.contains(briCarOrder.getOrderStatus())) {
                    CnvCarOrderDO cnvCarOrderDO = new CnvCarOrderDO();
                    convertToCnvCarOrderDO(briCarOrder, cnvCarOrderDO);
                    cnvCarOrderDOList.add(cnvCarOrderDO);
                }
            }
        }
        return cnvCarOrderDOList;
    }

    private void convertToCnvCarOrderDO(BriCarOrder briCarOrder, CnvCarOrderDO cnvCarOrderDO) {
        if (briCarOrder != null) {
            cnvCarOrderDO.setOrderNo(briCarOrder.getOrderNo());
            cnvCarOrderDO.setFromType(briCarOrder.getFromType());
            cnvCarOrderDO.setType(briCarOrder.getType());
            cnvCarOrderDO.setPublicOrPrivate(briCarOrder.getPublicOrPrivate());
            cnvCarOrderDO.setIsDomc(briCarOrder.getIsDomc());
            cnvCarOrderDO.setPreiumReason(briCarOrder.getPreiumReason());
            cnvCarOrderDO.setPreiumDetail(briCarOrder.getPreiumDetail());
            cnvCarOrderDO.setOrderStatus(briCarOrder.getOrderStatus());
            cnvCarOrderDO.setVehicleModel(briCarOrder.getVehicleModel());
            cnvCarOrderDO.setStartName(briCarOrder.getStartName());
            cnvCarOrderDO.setEndName(briCarOrder.getEndName());
            cnvCarOrderDO.setDepartureTime(briCarOrder.getDepartureTime());
            cnvCarOrderDO.setArriveTime(briCarOrder.getArriveTime());
            cnvCarOrderDO.setCallPhone(briCarOrder.getCallPhone());
            cnvCarOrderDO.setPsgName(briCarOrder.getPsgName());
            cnvCarOrderDO.setPsgPhone(briCarOrder.getPsgPhone());
            cnvCarOrderDO.setLinkerName(briCarOrder.getLinkerName());
            cnvCarOrderDO.setLinkerPhone(briCarOrder.getLinkerPhone());
            cnvCarOrderDO.setDriverPhone(briCarOrder.getDriverPhone());
            cnvCarOrderDO.setVehicleCard(briCarOrder.getVehicleCard());
            cnvCarOrderDO.setCreateBy(briCarOrder.getCreateBy());
            cnvCarOrderDO.setPayType(briCarOrder.getPayType());
            cnvCarOrderDO.setPaymentType(briCarOrder.getPaymentType());
            cnvCarOrderDO.setCityName(briCarOrder.getCityName());
            cnvCarOrderDO.setSourceType(briCarOrder.getSourceType());
            cnvCarOrderDO.setPlatCode(briCarOrder.getPlatCode());
            cnvCarOrderDO.setOutUserCode(briCarOrder.getOutUserCode());
            cnvCarOrderDO.setApproveStatus(briCarOrder.getApproveStatus());
            cnvCarOrderDO.setCostCenterName(briCarOrder.getCostCenterName());
            cnvCarOrderDO.setDistance(briCarOrder.getDistance());
            cnvCarOrderDO.setDuration(briCarOrder.getDuration());
            cnvCarOrderDO.setOutCompanyId(briCarOrder.getOutCompanyId());
            cnvCarOrderDO.setOutCreateTime(briCarOrder.getOutCreateTime());
            cnvCarOrderDO.setTotalPrice(briCarOrder.getTotalPrice());
            cnvCarOrderDO.setActualPrice(briCarOrder.getActualPrice());
            cnvCarOrderDO.setCouponPay(briCarOrder.getCouponPay());
            cnvCarOrderDO.setCompanyRealPay(briCarOrder.getCompanyRealPay());
            cnvCarOrderDO.setPersonRealPay(briCarOrder.getPersonRealPay());
            cnvCarOrderDO.setArrearsPay(briCarOrder.getArrearsPay());
            cnvCarOrderDO.setCompanyRealRefund(briCarOrder.getCompanyRealRefund());
            cnvCarOrderDO.setPersonRealRefund(briCarOrder.getPersonRealRefund());
            cnvCarOrderDO.setPayTime(briCarOrder.getPayTime());
            cnvCarOrderDO.setInApproveId(briCarOrder.getInApproveId());
            cnvCarOrderDO.setEmployeeNumber(briCarOrder.getEmployeeNumber());
            cnvCarOrderDO.setUseCarConfigId(briCarOrder.getUseCarConfigId());
            cnvCarOrderDO.setIsInvoice(briCarOrder.getIsInvoice());
            cnvCarOrderDO.setUseCarSrv(briCarOrder.getUseCarSrv());
            cnvCarOrderDO.setUserId(briCarOrder.getUserId());
            cnvCarOrderDO.setTenant(briCarOrder.getTenant());
            cnvCarOrderDO.setOrgPk(briCarOrder.getOrgPk());
            cnvCarOrderDO.setDepartment(briCarOrder.getDepartment());
            cnvCarOrderDO.setDeptPk(briCarOrder.getDeptPk());
            cnvCarOrderDO.setInCreateTime(briCarOrder.getInCreateTime());
            cnvCarOrderDO.setBxState(briCarOrder.getBxState());
            cnvCarOrderDO.setIsNote(briCarOrder.getIsNote());
            cnvCarOrderDO.setCategory(briCarOrder.getCategory());
            cnvCarOrderDO.setOtherInfo(briCarOrder.getOtherInfo());
            cnvCarOrderDO.setArriveCity(briCarOrder.getArriveCity());
            cnvCarOrderDO.setAirPlaneNo(briCarOrder.getAirPlaneNo());
            cnvCarOrderDO.setId(briCarOrder.getId());
        }
    }

    @Override
    public void updateIsNoteByOrderId(int orderId) {
        Map params=new HashMap();
        params.put("id",orderId);
        briCarOrderMapper.updateIsNoteByOrderId(params);
    }

    @Override
    public List<BriCarOrder> getCarOrdersByTimeRange(String tenantId, Date begin, Date end) {
        return briCarOrderMapper.getCarOrdersByTimeRange(tenantId, begin, end);
    }

    /**
     * 查询用车订单详情
     * @param params
     * @return
     */
    @Override
    public JSONObject getCarOrderJson(JSONObject params) {
        return null;
    }

    private List<BriCarOrderDTO> perfectCarOrderDTOs(List<BriCarOrderDTO> briCarOrderDTOS) {
        ArrayList<BriCarOrderDTO> briCarOrderDTOs = new ArrayList<>();
        if (briCarOrderDTOS != null && briCarOrderDTOS.size() > 0) {
            for (int i = 0; i < briCarOrderDTOS.size(); i++) {
                briCarOrderDTOs.add(OrderConvert.perfactCarDTO(briCarOrderDTOS.get(i)));
            }
        }
        return briCarOrderDTOs;
    }


    @Override
    public BriCarOrder getCarOrderJson(String tenant, String orderNo) {
        Wrapper<BriCarOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("tenant", tenant);
        wrapper.eq("order_no", orderNo);
        List<BriCarOrder> briCarOrders = briCarOrderMapper.selectList(wrapper);
        if (briCarOrders.size() > 0){
            return briCarOrders.get(0);
        }
        return null;
    }

    @Override
    public CnvCarOrderDO getBriCarOrderByOrderNo(String orderNo) {
        CnvCarOrderDO cnvCarOrderDO = new CnvCarOrderDO();
        BriCarOrder briCarOrder = briCarOrderMapper.getBriCarOrderByOrderNo(orderNo);
        convertToCnvCarOrderDO(briCarOrder, cnvCarOrderDO);
        return cnvCarOrderDO;
    }

    @Override
    public List<CnvCarOrderDO> getRelationOrders(String orderNo, String parentNo) {
        List<CnvCarOrderDO> orderList = new ArrayList<>();
        //用车没有退改单
        return orderList;
    }

    @Override
    public JSONArray getCarOrders(String userId, String bxState, String beginDate, String endDate, String tenant, Map<String, List<Map<String, String>>> canBeSeen) {
        List<BriCarOrder> briCarOrderList = this.getCarOrdersByBxState(userId, bxState, beginDate, endDate, tenant, canBeSeen);
        return getOrdersDetails(briCarOrderList, true);
    }

    @Override
    public JSONArray getCarOrders(String tenant, String orderNo) {
        Wrapper<BriCarOrder> wrapper = new EntityWrapper<>();
        wrapper.eq(BriCarOrder.TENANT, tenant);
        wrapper.eq(BriCarOrder.ORDER_NO, orderNo);
        List<BriCarOrder> briCarOrderList = this.selectList(wrapper);
        return getOrdersDetails(briCarOrderList, false);
    }

    private JSONArray getOrdersDetails(List<BriCarOrder> briCarOrderList, Boolean isFilter){
        JSONArray carOrderArr = new JSONArray();
        Iterator<BriCarOrder> iterator = briCarOrderList.iterator();
        while (iterator.hasNext()) {
            BriCarOrder briCarOrder = iterator.next();
            if (briCarOrder.getDepartureTime() == null || new Date().before(briCarOrder.getDepartureTime())) {
                // 未出行
                if (isFilter){
                    iterator.remove();
                    continue;
                }
            }
            JSONObject orderJSON = objToJSONObject(briCarOrder);

            //发票信息
            List<InvoiceRelationship> relationshipList = relationshipService.getRelationshipsByOrderNo(briCarOrder.getOrderNo());
            JSONArray relationArr = listToJSONArray(relationshipList);
            orderJSON.put("invoices", relationArr);

            carOrderArr.add(orderJSON);
        }
        return carOrderArr;
    }

    @Override
    public List<BriCarOrder> getCarOrdersByBxState(String userId, String bxState, String beginDate, String endDate, String tenant, Map<String, List<Map<String, String>>> canBeSeen){
        return briCarOrderMapper.getOrdersByBxState(userId, bxState, beginDate, endDate, tenant, canBeSeen);
    }

    /**
     * 将对象转成JSONObject
     * @param object
     * @return
     */
    private JSONObject objToJSONObject(Object object){
        String jsonString = JSONObject.toJSONString(object);
        return JSONObject.parseObject(jsonString);
    }

    /**
     * 将list转成JSONArray
     * @param list
     * @return
     */
    private JSONArray listToJSONArray(List list){
        String jsonString = JSONArray.toJSONString(list);
        return JSONArray.parseArray(jsonString);
    }
}
